/*
 * Copyright By Peak3
 * Copyright By c336bf6ff03a756989bb456b5b5e3271228d43ed38461eb5cb5755d17a2fc9b8
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package com.vv.tools.modules.auth.config;

import com.vv.tools.modules.auth.filter.CheckTokenFilter;
import com.vv.tools.modules.auth.handler.LoginAccessDefineHandler;
import com.vv.tools.modules.auth.handler.LoginAuthenticationHandler;
import com.vv.tools.modules.auth.handler.LoginFiledHandler;
import com.vv.tools.modules.auth.handler.LoginSuccessHandler;
import com.vv.tools.modules.auth.service.UserAuthService;

import java.util.Arrays;

import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @author liwen
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserAuthService userAuthService;

    private final LoginAccessDefineHandler loginAccessDefineHandler;

    private final LoginAuthenticationHandler loginAuthenticationHandler;

    private final LoginFiledHandler loginFiledHandler;

    private final LoginSuccessHandler loginSuccessHandler;

    private final CheckTokenFilter checkTokenFilter;

    @Value("${app.cors.allowed-origins:http://localhost:*,http://127.0.0.1:*,http://www.freemarker.online:*,https://www.freemarker.online:*}")
    private String allowedOrigins;

    @Value("${app.cors.allowed-methods:GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD}")
    private String allowedMethods;

    @Value("${app.cors.allowed-headers:*}")
    private String allowedHeaders;

    @Value("${app.cors.allow-credentials:true}")
    private boolean allowCredentials;

    @Value("${app.cors.max-age:3600}")
    private long maxAge;

    /**
     * 权限认证
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, AuthUrlConfig authUrlConfig) throws Exception {

        http
            // HttpSecurity#csrf
            .csrf(AbstractHttpConfigurer::disable)

            // 跨域配置
            .cors(cors -> cors.configurationSource(configurationSource()))

            // 安全匹配器
            //.securityMatcher("/**")

            // 前置过滤器
            // token 认证
            .addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class)

            // 授权
//            .addFilterBefore(checkAuthFilter, AuthorizationFilter.class)

            // HttpSecurity#authorizeHttpRequests
            // if success:
            // - SessionAuthenticationStrategy
            // - SecurityContextHolder
            // - RememberMeServices
            // - ApplicationEventPublisher
            // - AuthenticationSuccessHandler
            // if failure:
            // - SecurityContextHolder
            // - RememberMeServices
            // - AuthenticationFailureHandler
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers(authUrlConfig.getPermit().toArray(new String[0])).permitAll()
                .anyRequest().authenticated()
            )

            // 记住我
            //.rememberMe((remember) -> remember
            //    .rememberMeServices(rememberMeServices)
            //)

            // 请求缓存
            //.requestCache(cache -> cache
            //    .requestCache(requestCache)
            //)

            // HttpSecurity#httpBasic
            .httpBasic(Customizer.withDefaults())

            // HttpSecurity#formLogin
            .formLogin(formLogin -> formLogin
                .loginPage(authUrlConfig.getLoginUrl())
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFiledHandler)
                .permitAll()
            )

            // 登出
            .logout(logout -> logout
                .logoutUrl(authUrlConfig.getLogoutUrl())
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .permitAll()
            )

            // 异常处理
            .exceptionHandling(exceptionHandling -> exceptionHandling
                .authenticationEntryPoint(loginAuthenticationHandler)
                .accessDeniedHandler(loginAccessDefineHandler)
            );
        return http.build();
    }

    /**
     * 认证
     */
    @Bean
    public AuthenticationManager authenticationManager(PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userAuthService);
        authenticationProvider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(authenticationProvider);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 跨域配置
     */
    CorsConfigurationSource configurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // 允许的源 - 从配置文件读取
        String[] origins = allowedOrigins.split(",");
        configuration.setAllowedOriginPatterns(Arrays.asList(origins));
        
        // 允许的HTTP方法 - 从配置文件读取
        String[] methods = allowedMethods.split(",");
        configuration.setAllowedMethods(Arrays.asList(methods));
        
        // 允许的请求头 - 从配置文件读取
        if ("*".equals(allowedHeaders)) {
            configuration.setAllowedHeaders(Arrays.asList("*"));
        } else {
            String[] headers = allowedHeaders.split(",");
            configuration.setAllowedHeaders(Arrays.asList(headers));
        }
        
        // 暴露的响应头
        configuration.setExposedHeaders(Arrays.asList(
            "Access-Control-Allow-Origin",
            "Access-Control-Allow-Credentials",
            "Access-Control-Expose-Headers",
            "Date",
            "Server",
            "Content-Type"
        ));
        
        // 允许携带凭证
        configuration.setAllowCredentials(allowCredentials);
        
        // 预检请求缓存时间（秒）
        configuration.setMaxAge(maxAge);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


}

